<template>
  <div class="login_container">
    <div class="login_box">
      <div class="avatar_box">
        <img src="../assets/logo.jpg" alt="" />
      </div>
      <el-form ref="loginFormRef" :model="loginForm" :rules="loginFormRules" label-width="0px" class="login_form">
        <el-form-item>
          <el-select v-model="role" placeholder="选择登录角色">
            <el-option label="老师" value="teacher"></el-option>
            <el-option label="学生" value="student"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="username">
          <el-input placeholder="请输入用户名" :prefix-icon="UserFilled" size="large" v-model="loginForm.username"></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input type="password" placeholder="请输入密码" :prefix-icon="MoreFilled" size="large" v-model="loginForm.password"></el-input>
        </el-form-item>
        <el-form-item class="btns">
          <el-button type="primary" @click="login">登录</el-button>
          <el-button type="info" @click="signup">注册</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import { MoreFilled, UserFilled } from "@element-plus/icons-vue";
import axios from "axios";
import { BASE_URL } from '@/config'; // 引入配置

export default {
  computed: {
    MoreFilled() {
      return MoreFilled;
    },
    UserFilled() {
      return UserFilled;
    }
  },
  data() {
    return {
      role: 'teacher', // 默认选择老师
      loginForm: {
        username: '',
        password: '',
      },
      loginFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 12, message: '请输入用户名长度为3到12个字符', trigger: 'blur' },
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
        ]
      },
    };
  },
  mounted() {
    if (this.$route.query.username) {
      this.loginForm.username = this.$route.query.username;
    }
  },
  methods: {
    signup() {
      window.sessionStorage.clear();
      this.$router.push('/signUp');
    },
    async login() {
      let res;
      await this.$refs.loginFormRef.validate(async (valid) => {
        if (!valid) return;
        try {
          const endpoint = this.role === 'teacher'
              ? `${BASE_URL}/teacher/login`
              : `${BASE_URL}/student/login`;


          console.log('登录信息:', this.loginForm.username, this.loginForm.password);
          console.log('即将发送 POST 请求到:', endpoint);

          if(this.role === 'teacher'){
            res = await axios.post(endpoint, {
              tch_id: this.loginForm.username, // 确保字段名与后端一致
              tch_password: this.loginForm.password, // 同上
            }, {
              headers: {
                'Content-Type': 'application/json'
              }
            });

          }
          if(this.role === 'student'){
            res = await axios.post(endpoint, {
              stu_id: this.loginForm.username, // 确保字段名与后端一致
              stu_password: this.loginForm.password, // 同上
            }, {
              headers: {
                'Content-Type': 'application/json'
              }
            });

          }


          console.log('POST 请求已发送，收到响应:', res);

          // console.log(this.loginForm);

          if (res.data.code === 200) {
            this.$message.success("登录成功！");

            const username = res.data.user ? res.data.user.username : this.loginForm.username;

            window.sessionStorage.setItem('userId', username);
            if (this.role === 'teacher') {
              this.$router.push({ path: "/teachercoursepage", query: { username: this.loginForm.username } });
            } else if (this.role === 'student') {
              this.$router.push({ path: "/coursepage", query: { username: this.loginForm.username } });
            }
          } else {
            this.$message.error("登录失败！");
          }
        } catch (error) {
          this.handleError(error);
        }
      });
    },
    handleError(error) {
      if (error.response) {
        console.error('响应错误', error.response.data);
      } else if (error.request) {
        console.error('请求错误', error.request);
      } else {
        console.error('错误', error.message);
      }
    }
  },
};
</script>

<style scoped lang="less">
.login_container {
  height: 100%;
  position: relative;
  background-image: url('../assets/动图.gif');
  background-size: cover;
  background-position: center;
}

.login_box {
  width: 450px;
  height: 400px;
  background-color: rgba(255, 255, 255, 0.8);
  border-radius: 3px;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
}

.avatar_box {
  height: 130px;
  width: 130px;
  background-color: #fff;
  border: 1px solid #eee;
  border-radius: 50%;
  padding: 10px;
  box-shadow: 0 0 10px #ddd;
  position: absolute;
  left: 50%;
  transform: translate(-50%, -50%);
}

.avatar_box img {
  height: 100%;
  width: 100%;
  border-radius: 50%;
  background-color: #eee;
}

.login_form {
  position: absolute;
  bottom: 0;
  width: 100%;
  padding: 0 20px;
  box-sizing: border-box;
}

.btns {
  display: flex;
  justify-content: space-between;
}
</style>
